package cn.hfatec.shms.web.xc.xcGjjl.action;

import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.system.userRole.service.UserRoleService;
import cn.hfatec.shms.web.xc.xcGsgj.model.XcGsgjParams;
import cn.hfatec.shms.web.xc.xcGsgj.service.XcGsgjService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;


import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.web.xc.xcGjjl.model.XcGjjlParams;
import cn.hfatec.shms.web.xc.xcGjjl.model.XcGjjl;
import cn.hfatec.shms.web.xc.xcGjjl.service.XcGjjlService;
import cn.hfatec.shms.base.ShmsBaseAction;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/xc/xcGjjl")
public class XcGjjlAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "XcGjjlService")
    private XcGjjlService xcGjjlService;
    //服务层
    @Resource(name = "XcGsgjService")
    private XcGsgjService xcGsgjService;
    //注入Dao层
    @Resource(name = "UserRoleService")
    private UserRoleService userRoleService;
    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(XcGjjlParams xcGjjlParams, Page page, Model model,  HttpServletRequest request) throws NotAuthException {
        User user = (User) request.getSession().getAttribute(SysContant.LOGIN_USER_SESSION);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        List userRole= userRoleService.queryUserRoleByUserId(user.getLoginName());

        String role="";
        for(Object roleId : userRole) {//其内部实质上还是调用了迭代器遍历方式，这种循环方式还有其他限制，不建议使用。
            role += roleId.toString() + ",";
        }
        if(!role.contains("FP")){
            xcGjjlParams.setUserName(user.getUserName());}

        Table table = xcGjjlService.queryXcGjjlTable(xcGjjlParams, page);
        model.addAttribute("lqztList", CodeInfoCache.getCodeInfo(CodeType.LQZT_TYPE));
        model.addAttribute("vipList", CodeInfoCache.getCodeInfo(CodeType.VIP_RAND));
        model.addAttribute("xcGjjlsTable", table);
        model.addAttribute("xcGjjlParams", xcGjjlParams);
        return "/xc/xcGjjl/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(XcGjjlParams xcGjjlParams, Page page, Model model,  HttpServletRequest request) {
        try {
            list(xcGjjlParams, page, model,request);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/xc/xcGjjl/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Integer id, Model model, HttpServletRequest request) {
        try {
            User user = (User) request.getSession().getAttribute(SysContant.LOGIN_USER_SESSION);
            if (user == null) {
                throw new NotAuthException("用户未授权");
            }
            XcGjjl xcGjjl = xcGjjlService.getGsgj(id);
            if (xcGjjl == null)
                xcGjjl = new XcGjjl();
            xcGjjl.setUserName(user.getUserName());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String gjDate = df.format(new Date());
            xcGjjl.setGjDate(gjDate);
            model.addAttribute("lqztList", CodeInfoCache.getCodeInfo(CodeType.LQZT_TYPE));
            model.addAttribute("vipList", CodeInfoCache.getCodeInfo(CodeType.VIP_RAND));
            model.addAttribute("xcGjjl", xcGjjl);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/xc/xcGjjl/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            XcGjjl xcGjjl = xcGjjlService.getXcGjjl(id);
            model.addAttribute("lqztList", CodeInfoCache.getCodeInfo(CodeType.LQZT_TYPE));
            model.addAttribute("vipList", CodeInfoCache.getCodeInfo(CodeType.VIP_RAND));
            model.addAttribute("xcGjjl", xcGjjl);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/xc/xcGjjl/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteXcGjjl(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            xcGjjlService.deleteXcGjjlBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveXcGjjl(@Valid XcGjjl xcGjjl, BindingResult result) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            xcGjjlService.saveXcGjjl(xcGjjl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据XcGjjl保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 导出excel
     */
    @RequestMapping("/export")
    @ResponseBody
    public String export(XcGjjlParams xcGjjlParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            xcGjjlService.exportExcel(xcGjjlParams, request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
}
